﻿using Hangfire;
using Hangfire.Storage.SQLite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace ORS.OrderRobot.Foundation.Hangfire
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册 Hangfire 使用 MySQL 存储
        /// </summary>
        public static IServiceCollection AddHangfireWorkerManager(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            var connectionString = configuration.GetConnectionString(Consts.ConnectName);

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception("HangfireConnection not found in configuration.");
            }

            services.AddHangfire(config =>
            {
                /*
                config.UseStorage(new MySqlStorage(connectionString,new MySqlStorageOptions
                {
                    TablesPrefix = "Hangfire_",
                }));
                */
                config
                    .UseSimpleAssemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseSQLiteStorage();

            });
            services.TryAddSingleton<IBackgroundWorkerManager, HangfireBackgroundWorkerManager>();
            services.TryAddSingleton<IBackgroundJobManager, DefaultBackgroundJobManager>();
            services.AddHangfireServer(options =>
            {
                options.ServerTimeout = TimeSpan.FromMinutes(15);
                options.SchedulePollingInterval = TimeSpan.FromSeconds(5);
            });
            return services;
        }
    }
}

